<template>
  <a-card>
    <Table ref="tableRef" :columns="columns" :data="loadData" :alert="false" bordered>
      <template #operator>
        <div class="table-search">
          <div>
            <span class="table-search-box">
              名称：
              <a-input v-model:value="searchValue" placeholder="请输入仓库名称" style="width: 360px" allowClear>
                <template #prefix>
                  <SvgIcon class="iconDef" :name="'search'" :color="'#d9d9d9'" width="16" height="16" />
                </template>
              </a-input>
            </span>

            <span class="table-search-box">
              制品类型：
              <a-select
                style="width: 296px"
                :options="artifactTypeOptions"
                v-model:value="selectValue"
                placeholder="请选择"
                allowClear
              >
                <template #suffixIcon>
                  <CaretDownOutlined style="color: #6b84a5" />
                </template>
              </a-select>
            </span>
          </div>
          <div class="table-search-btn">
            <a-button class="actionBtn" type="primary" ghost @click="tableRef.refresh(true)">
              <SvgIcon class="iconDef" :name="'search'" :color="'#2590FF'" width="16" height="16" />
              查询
            </a-button>

            <a-button class="actionBtn" type="primary" ghost @click="refreshTable">
              <SvgIcon class="iconDef" :name="'refresh'" :color="'#2590FF'" width="16" height="16" />
              重置
            </a-button>
          </div>
        </div>
        <div style="margin-top: 16px">
          <a-button type="primary" @click="addRepository">
            <PlusOutlined />
            新增制品仓库
          </a-button>
        </div>
      </template>
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.dataIndex === 'index'"> {{ index + 1 }} </template>
        <template v-if="column.dataIndex === 'serverAddress'">
          <div class="table-copy">
            <span class="table-copy-text ellipsis" :title="`${record.serverAddress}${record.instanceRepositoryName}`">{{
              `${record.serverAddress}${record.instanceRepositoryName}`
            }}</span>
            <span
              class="table-copy-icon"
              @click="copyAddress(`${record.serverAddress}${record.instanceRepositoryName}`)"
            >
              <SvgIcon class="iconDef" :name="'copy'" :color="'#8c9fb9'" width="16" height="16" />
            </span>
          </div>
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="table-operation">
            <a @click="repositoryDetial(record)">详情</a>
            <a
              @click="editRepository(record)"
              v-if="
                hasPermission({
                  objectId: record.uuid,
                  objectType: ResourceType.repository,
                  role: ArtifactRole.manager,
                })
              "
              >编辑</a
            >
            <a @click="manage(record)">管理</a>
            <a
              @click="deleteRepository(record)"
              v-if="
                hasPermission({
                  objectId: record.uuid,
                  objectType: ResourceType.repository,
                  role: ArtifactRole.manager,
                })
              "
              >删除</a
            >
          </div>
        </template>
      </template>
    </Table>
  </a-card>
  <BasicModal
    ref="addAllocation"
    :title="`${ModalName[modelType]}制品仓库`"
    width="800px"
    :confirmLoading="editArtifactRepositoryLoading"
    @emit-callback-fn="modalCallbackFn($event)"
  >
    <template #content>
      <SchemaForm ref="formRef" />
    </template>
  </BasicModal>
</template>

<script setup lang="ts">
import { PlusOutlined, CaretDownOutlined } from '@ant-design/icons-vue';
import {
  queryArtifactRespositoryPageListFun,
  addArtifactRespositoryPageListFun,
  putArtifactRespositoryPageListFun,
  deleteArtifactRespositoryPageListFun,
  getRespositoryUrl,
} from '@/api/artifactRepository';
import { ModalName, PordDefaultData, ModalType, RepositoryEnum } from '@/enums/commonEnum';
import { artifactTypeOptions, storagePolicyOptions, validatorCode } from '@/settings/commonSettings';
import { useForm } from '@/components/SchemaForm/index';
import type { FormSchema } from '@/components/SchemaForm';
import { Modal, message } from 'ant-design-vue';
import { createVNode } from 'vue';
import { copyTextValue } from '@/utils';
import { useArtifactRepositoryStore } from '@/store/modules/artifactRepository';
import { ResourceType } from '@/enums/pipelineEnum';
import { ArtifactRole } from '@/enums/artifactRepositoryEnum';
import { usePermissionStore } from '@/store/modules/permission';
import { usePermission } from '@/hooks/web/usePermission';
const artifactRepositoryStore = useArtifactRepositoryStore();
const { setArtifactObjData } = artifactRepositoryStore;

const { hasPermission } = usePermission();
const router = useRouter();
const tableRef = ref<any>(null);
const searchValue = ref<string>('');
const selectValue = ref<string | undefined>(undefined);
// 复制地址
const copyAddress = async (address: string): Promise<void> => {
  copyTextValue(address);
};
const permStore = usePermissionStore();
const editArtifactRepositoryLoading = ref<boolean>(false);

// 异步加载数据
const loadData = async (parameter: any) => {
  const parameObj = {
    currentPage: parameter.current,
    pageSize: parameter.size,
    condition: {
      condition: searchValue.value,
      artifactType: selectValue.value,
      dataSource: PordDefaultData.artifactRepository,
    },
  };
  const data = await getList(parameObj);
  return data;
};

// 表格标题
const columns = [
  { dataIndex: 'index', title: '序号', align: 'center', width: 60 },
  { dataIndex: 'artifactName', title: '仓库名称', align: 'center', ellipsis: true },
  { dataIndex: 'artifactType', title: '制品类型', align: 'center', ellipsis: true },
  { dataIndex: 'serverAddress', title: '仓库地址', align: 'center', ellipsis: true, width: '35%' },
  { dataIndex: 'creator', title: '创建者', align: 'center', ellipsis: true },
  { dataIndex: 'createTime', title: '创建时间', align: 'center', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 213,
  },
];
const modelType = ref<ModalType>(ModalType.add);
//仓库地址的默认值
const hostName = ref<string>('');
// 表单
const [SchemaForm, formRef] = useForm({
  schemas: [
    {
      field: 'artifactName',
      label: '仓库名称',
      labelWidth: 84,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'Input',
      dynamicDisabled: () => {
        return [ModalType.detail].includes(modelType.value);
      },
    },

    {
      field: 'artifactType',
      label: '仓库类型',
      labelWidth: 84,
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: () => {
        return {
          options: artifactTypeOptions,
          onChange: (e: string) => {
            getShowUrl(e);
          },
        };
      },
      component: 'Select',
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(modelType.value);
      },
    },

    {
      field: 'artifactCode',
      label: '仓库编码',
      labelWidth: 84,
      colProps: {
        span: 24,
      },
      rules: [
        {
          required: true,
          trigger: ['change', 'blur'],
          validator: (_, value: any) => {
            return new Promise((resolve, reject) => {
              if (!value) {
                reject(new Error('仓库编码不能为空'));
              } else if (!validatorCode.test(value)) {
                reject(new Error('请输入长度不超过50字符的小写字母、数字或中划线，且不能以中划线开头或结尾。'));
              } else {
                resolve();
              }
            });
          },
        },
      ],
      componentProps: ({ formModel }) => {
        return {
          onChange: (e: any) => {
            formModel.artifactEndCode = e.target.value;
          },
        };
      },
      component: 'Input',
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(modelType.value);
      },
    },

    {
      field: 'serverAddress',
      label: '仓库地址',
      labelWidth: 84,
      required: true,
      colProps: {
        span: 16,
      },
      component: 'Input',
      dynamicDisabled: true,
    },
    {
      field: 'artifactEndCode',
      required: false,
      labelWidth: 0,
      colProps: {
        span: 8,
      },
      colon: false,
      component: 'Input',
      dynamicDisabled: true,
    },
    {
      field: 'storageStrategy',
      label: '存储策略',
      labelWidth: 90,
      required: true,
      colProps: {
        span: 24,
      },
      vIf: ({ formModel }) => {
        return (formModel.artifactType as unknown as RepositoryEnum) == RepositoryEnum.MAVEN;
      },
      componentProps: {
        options: storagePolicyOptions,
      },
      component: 'CheckboxGroup',
      dynamicDisabled: () => {
        return [ModalType.edit, ModalType.detail].includes(modelType.value);
      },
    },
    {
      field: 'description',
      label: '仓库描述',
      labelWidth: 84,
      required: true,
      colProps: {
        span: 24,
      },
      component: 'InputTextArea',
      dynamicDisabled: () => {
        return [ModalType.detail].includes(modelType.value);
      },
    },
  ] as FormSchema[],
});

const getList = async (parameObj: any) => {
  return await queryArtifactRespositoryPageListFun(parameObj).then((res) => {
    const data = {
      total: res.totalCount,
      current: res.currentPage,
      pageSize: res.pageSize,
      records:
        res?.records?.map((v: any) => {
          return {
            ...v,
            artifactEndCode: v.instanceRepositoryName,
            serverAddress: v.serverAddress.split(v.instanceRepositoryName)[0],
          };
        }) || [],
    };
    return data;
  });
};

//刷新表格数据
const refreshTable = () => {
  searchValue.value = '';
  selectValue.value = undefined;
  tableRef.value.refresh(true);
};

const modalCallbackFn = async (obj: any) => {
  const data = await formRef.validate();
  editArtifactRepositoryLoading.value = true;
  let parameObj: OperationManagement.addArtifactPageListParams = {
    ...data,
    serverAddress: `${data.serverAddress}${data.artifactCode}`,
    storageStrategy: data?.storageStrategy ? data?.storageStrategy.join(',') : '',
    projectCode: PordDefaultData.projectCode,
    projectName: PordDefaultData.systemBuiltInProject,
    dataSource: PordDefaultData.artifactRepository,
    openScope: PordDefaultData.openScope,
  };

  if (modelType.value === ModalType.add) {
    await addArtifactRespositoryPageListFun(parameObj)
      .then(async () => {
        message.success('添加成功');
        await permStore.fetchPermissionList();
        tableRef.value.refresh(true);
        addAllocation.value.hideModal();
      })
      .finally(() => {
        editArtifactRepositoryLoading.value = false;
      });
  }

  if (modelType.value === ModalType.edit) {
    if ('serverAddress' in parameObj) {
      delete parameObj.serverAddress;
    }
    if ('artifactEndCode' in parameObj) {
      delete parameObj.artifactEndCode;
    }
    await putArtifactRespositoryPageListFun({ uuid: obj.propsData.uuid, ...parameObj })
      .then(() => {
        message.success('编辑成功');
        tableRef.value.refresh(true);
        addAllocation.value.hideModal();
      })
      .finally(() => {
        editArtifactRepositoryLoading.value = false;
      });
  }
};

const addAllocation: any = ref(null);

// 获取制品仓库前缀
const getShowUrl = async (key: string) => {
  await getRespositoryUrl(key).then((res) => {
    hostName.value = res;
    formRef.setFieldsValue({ serverAddress: hostName.value });
  });
};

//表格详情
const repositoryDetial = (record: any) => {
  modelType.value = ModalType.detail;
  let obj = { ...record, storageStrategy: record?.storageStrategy ? record.storageStrategy.split(',') : [] };
  addAllocation.value.showModal(record, '关闭');
  nextTick(() => {
    formRef.setFieldsValue(obj);
  });
};

//添加制品仓库
const addRepository = () => {
  modelType.value = ModalType.add;
  addAllocation.value.showModal();
};

//编辑仓库
const editRepository = (record: any) => {
  modelType.value = ModalType.edit;
  let obj = { ...record, storageStrategy: record?.storageStrategy ? record.storageStrategy.split(',') : [] };
  addAllocation.value.showModal(record);
  nextTick(() => {
    formRef.setFieldsValue(obj);
  });
};

//删除仓库
const deleteRepository = (record: any) => {
  Modal.confirm({
    title: '提示',
    icon: '',
    centered: true,
    content: createVNode(
      'div',
      { style: 'color:black;' },
      `确定要删除“制品仓库：${record.artifactName}”这一项数据吗？`,
    ),
    async onOk() {
      await deleteArtifactRespositoryPageListFun(record.uuid).then(async () => {
        message.success('删除成功');
        await permStore.fetchPermissionList();
        tableRef.value.refresh(true);
      });
    },
    onCancel() {},
  });
};

//管理
const manage = (record: Recordable) => {
  setArtifactObjData(record);
  router.push(`/system/artifactRepository/artifactManage/${record.artifactType}/${record.artifactCode}`);
};
</script>

<style scoped lang="less">
.table-search {
  border-bottom: 1px solid #e7eff8;
  padding-bottom: 16px;
}
.table-copy {
  display: flex;
  align-items: center;
  position: relative;
  .table-copy-text {
    margin-right: 5px;
    display: inline-block;
    width: 90%;
  }
  .table-copy-icon {
    cursor: pointer;
    position: absolute;
    right: 5px;
    top: 50%;
    transform: translate(0, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
